
include( "shared.lua" )

Spawns_RED = {}
Spawns_BLUE = {}

function GM:PlayerSpawn( ply )

	self.BaseClass:PlayerSpawn( ply )
	
	ply:SpawnAtTeam( ply:Team() )
	
end

function GM:CheckRoundEnd()

	if ( !GAMEMODE:InRound() ) then return end
	
	local ingoal = GetGlobalBool("BallInGoal")
	local red = GetGlobalBool("RedWIN")
	local blue = GetGlobalBool("BlueWIN")

	if ingoal then
	
		if red and not blue then GAMEMODE:RoundEndWithResult( TEAM_RED ) end
		if blue and not red then GAMEMODE:RoundEndWithResult( TEAM_BLUE ) end
		
	end

	timer.Create( "CheckRoundEnd", 1, 0, function() GAMEMODE:CheckRoundEnd() end )

end

function GM:OnRoundStart( num )

	UTIL_UnFreezeAllPlayers()
	
	LoadSpawnTable()

end

function GM:OnRoundEnd( num )

	SetGlobalBool("BallInGoal", false)
	SetGlobalBool("RedWIN", false)
	SetGlobalBool("BlueWIN", false)
	
end

function LoadSpawnTable()

	Spawns_RED = ents.FindByClass("info_player_red")
	Spawns_BLUE = ents.FindByClass("info_player_blue")
	
end

local meta = FindMetaTable("Player")

function meta:SpawnAtTeam( team )

	LoadSpawnTable()

	if team == TEAM_RED then
	
		local spawn = table.Random(Spawns_RED)
		local spawnpos = spawn:GetPos()
		
		self:SetPos(spawnpos)
		
	elseif team == TEAM_BLUE then
	
		local spawn = table.Random(Spawns_BLUE)
		local spawnpos = spawn:GetPos()
		
		self:SetPos(spawnpos)
		
	else
	
		self:SetPos( Vector( 0, 0, 0 ) )
		
	end
	
end